import { App } from 'vue'
import { ElMessage } from 'element-plus'

const regObj = {
    reg1: /^\+?[1-9][0-9]*$/,
    reg2: /^([1-9]\d{0,2})$/
}

const msgObj = {
    msg1: '请输入正整数',
    msg2: '请输入3位以内正整数'
}

export default (app: App<Element>): void => {
    app.directive('num', {
        mounted(el, binding, vnode: any) {
            console.log(vnode)
            const reg = new RegExp(binding.arg === 'reg' ? regObj[`reg${binding.value}`] : (/^\+?[1-9][0-9]*$/))
            el.addEventListener('input', (event: any) => {
                // console.log(event.target.value)
                if (!reg.test(event.target.value)) {
                    event.target.value = ''
                    ElMessage({
                        message: msgObj[`msg${binding.value}`],
                        type: 'error',
                    })
                }
                vnode.ctx.emit('update:modelValue', event.target.value)
            })
            el.addEventListener('change', (event: any) => {
                el.dispatchEvent(new Event('change ', { bubbles: true }))
                vnode.ctx.emit('update:modelValue', event.target.value)
            })
            el.addEventListener('clear', (event: any) => {
                el.dispatchEvent(new Event('clear ', { bubbles: true }))
                vnode.ctx.emit('update:modelValue', event.target.value)
            })
            el.addEventListener('focus', (event: any) => {
                el.dispatchEvent(new Event('focus ', { bubbles: true }))
                vnode.ctx.emit('update:modelValue', event.target.value)
            })
            el.addEventListener('blur', (event: any) => {
                el.dispatchEvent(new Event('blur ', { bubbles: true }))
                vnode.ctx.emit('update:modelValue', event.target.value)
            })
        }
    })
}
